使得线程等待,只有满足某条件时,才执行num个线程
条件 = 递归锁 + wait 功能
import threading
con = threading.Condition() # 条件对象
con.wait() # 线程在这里等待着
con.acquire() # 上锁
con.release() # 解锁
con.notify(5) # 发送信号给 wait 允许5个线程执行
con.notify_all() # 发送信号给 wait 允许全部线程执行
1. 手动释放线程的个数例子
import threading
def run(n):
con.acquire()
con.wait() # 线程在这里等待着
print("执行了线程: %s" % n)
con.release()
con = threading.Condition() # 条件 = 递归锁 + wait 功能
for i in range(10):
t = threading.Thread(target=run, args=(i,))
t.start()
while True:
inp = input('>>>')
if inp == 'q':
break
con.acquire()
if inp == 'all':
con.notify_all() # 发送信号给 wait 允许全部线程执行
else:
con.notify(int(inp)) # notify(5) -> 发送信号给 wait 允许5个线程执行
con.release()